package edu.ccut.saturn.basecomponent.database;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


public class SaturnSQLHandlerFactory {
	private static Map<String, ISaturnSQLHandler> handlerMap = new HashMap<String, ISaturnSQLHandler>();
	private static final String DIRECTORY_TYPE_FILE_NAME = "handler.properties";
	static {
		initalHandler();
	}
	
	private static void initalHandler() {
		Properties properties = new Properties();
		InputStream in = null;

		try {
			in = SaturnSQLHandlerFactory.class
					.getResourceAsStream(DIRECTORY_TYPE_FILE_NAME);

			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		for (Enumeration<?> propertyNames = properties.propertyNames(); propertyNames
				.hasMoreElements();) {

			String key = (String) propertyNames.nextElement();
			String className = properties.getProperty(key);

			try {
				Object builder = Class.forName(className).newInstance();
				
				if (builder instanceof ISaturnSQLHandler) {
					handlerMap.put(key, (ISaturnSQLHandler)builder);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private SaturnSQLHandlerFactory() {
		
	}
	
	public static ISaturnSQLHandler getSaturnSQLHandler(String operation, String dbType) {
		ISaturnSQLHandler handler = handlerMap.get(operation + "_" + dbType);
		
		if (handler != null) {
			return handler;
		}
		
		return handlerMap.get(operation);
	}
}
